<!--  usermgr 用户管理 -->
<template>
  <a-card
    :bordered="false"
    :body-style="{ 'padding-bottom': '0px' }"
    :style="{ margin: '6px', }"
  >
    <a-form
      ref="searchFormRef"
      name="advanced_search"
      :model="searchFormState"
      class="ant-advanced-search-form"
    >
      <a-row :gutter="24">
        <a-col :span="6">
          <a-form-item label="部门" name="DeptID">
            <!-- deptmgrList -->
            <a-select
              v-model:value="searchFormState.DeptID"
              style="width: 100%"
              placeholder="请选择部门"
              :options="deptmgrList"
            ></a-select>
          </a-form-item>
        </a-col>
        <a-col :span="4">
          <a-form-item label="用户角色" name="RoleID">
            <!--   <a-input
              v-model:value="searchFormState.RoleID"
              placeholder="请输入角色ID"
              @keyup.enter="tableRef.refresh(true)"
            /> -->
            <a-select
              v-model:value="searchFormState.RoleID"
              style="width: 100%"
              placeholder="请选择用户角色"
              :options="formRoleList"
            ></a-select>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="用户名称" name="UserName">
            <a-input
              v-model:value="searchFormState.UserName"
              placeholder="请输入用户名称"
              @keyup.enter="tableRef.refresh(true)"
            />
          </a-form-item>
        </a-col>
        <a-col :span="3">
          <a-form-item label="用户状态" name="IsEnable">
            <a-select
              v-model:value="searchFormState.IsEnable"
              style="width: 100%"
              placeholder="请选择用户状态"
              @change="tableRef.refresh(true)"
              :options="[
                {
                  value: -1,
                  label: '全部',
                },
                {
                  value: 0,
                  label: '禁用',
                },
                {
                  value: 1,
                  label: '启用',
                },
              ]"
            ></a-select>
          </a-form-item>
        </a-col>
        <a-col :span="5">
          <a-button
            class="mr10"
            type="primary"
            @click="tableRef.refresh(true)"
            v-show="hasRole(route.meta.RolePower)"
            >查询</a-button
          >
          <a-button
            class="xn-mg08"
            @click="reset"
            v-show="hasRole(route.meta.RolePower)"
            >重置</a-button
          >
        </a-col>
      </a-row>
     
    </a-form>
  </a-card>
  <a-card :bordered="false" style="margin: 6px">
    <m-table
      ref="tableRef"
      :columns="columns"
      :data="loadData"
      :alert="options.alert.show"
      bordered
      :row-key="(record) => record.ID"
      :tool-config="toolConfig"
      :row-selection="options.rowSelection"
      :show-pagination="true"
      :scroll="{ x: 'max-content' }"
    >
      <template #operator>
        <a-space>
          <a-button
            v-show="hasAddRole(route.meta.RolePower)"
            type="primary"
            @click="formRef.onOpen()"
          >
            <template #icon><plus-outlined /></template>
            新增用户
          </a-button>
        </a-space>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.dataIndex === 'IsEnable'">
          <a-switch
            :disabled="!hasEditRole(route.meta.RolePower)||record.ID===1"
            :checked="record.IsEnable === 1"
            @click="changeEnable($event, record)"
          />
        </template>
        <template v-if="column.dataIndex === 'UpdateTime'">
          {{ transitionTime(record.UpdateTime) }}
        </template>
        <template v-if="column.dataIndex === 'RoleID'">
          {{ formRoleList.find((item) => item.value === record.RoleID)?.label }}

        </template>
        <template v-if="column.dataIndex === 'DeptID'">
          {{ deptmgrList.find((item) => item.value === record.DeptID)?.label }}

        </template>
        <template v-if="column.dataIndex === 'action'">
          <a-space>
            <a-button
              type="link"
              @click="changePassword(record)"
              v-show="hasEditRole(route.meta.RolePower)"
              >修改密码</a-button
            >
            <a-divider type="vertical" v-show="hasEditRole(route.meta.RolePower)&&hasEditRole(route.meta.RolePower)&&record.ID!==1"/>
            <a-button
              type="link"
              @click="formRef.onOpen(record)"
              v-show="hasEditRole(route.meta.RolePower)&&record.ID!==1"
              >编辑</a-button
            >
            <a-divider type="vertical"  v-show="hasEditRole(route.meta.RolePower)&&record.ID!==1&&hasDeleteRole(route.meta.RolePower)"/>
            <a-popconfirm
              title="确定删除？"
              @confirm="deleteModule(record)"
              ok-text="确定"
              cancel-text="关闭"
            >
              <a-button
                type="link"
                danger
                size="small"
                v-show="hasDeleteRole(route.meta.RolePower)&&record.ID!==1"
                >删除</a-button
              >
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </m-table>
  </a-card>
  <a-modal
    class="default"
    v-model:open="open"
    :title="record.UserName + '修改密码'"
    @ok="handleOk"
    :zIndex="100000"
  >
    <a-form
      ref="passwordFormRef"
      name="passwordFormRef"
      :model="passwordFormState"
      class="ant-advanced-search-form"
      :rules="formRules"
    >
      <a-form-item label="新密码" name="NewPwd">
        <a-row :gutter="24">
          <a-col :span="16">
            <a-input
              type="password"
              :vlaue="passwordFormState.NewPwd"
              placeholder="请输入新密码"
              allow-clear
              style="width: 100%"
              @input="setNewPassword"
            />
          </a-col>
          <a-col :span="8" :offset="0">
            <div class="progress" v-show="percent !== 3">
              <div :class="{ progress_c_1: percent > 0 }"></div>
              <div :class="{ progress_c_2: percent > 1 }"></div>
              <div :class="{ progress_c_3: percent > 2 }"></div>
            </div>
            <div class="checkoutBox" v-show="percent === 3">
              <div class="checkout"><CheckOutlined style="color: #fff" /></div>
            </div>
          </a-col>
        </a-row>
      </a-form-item>
    </a-form>
  </a-modal>

  <!-- -->
  <Form ref="formRef" @successful="tableRef.refresh(true)" :deptmgrList="_deptmgrList" :formRoleList="_formRoleList"/>
</template>
    
<script setup name="deptmgr">
import { useRoute } from "vue-router";
import Form from "./form.vue";
import { onMounted, ref } from "vue";
import { message } from "ant-design-vue";
import usermgrApi from "@/api/systemManagement/usermgrApi";
import rolemgrApi from "@/api/systemManagement/rolemgrApi";
import deptmgrApi from "@/api/systemManagement/deptmgrApi";
import { transitionTime } from "@/utils/time.js";
import { required } from "@/utils/formRules";
import loginApi from "@/api/loginApi";
import { CheckOutlined } from "@ant-design/icons-vue";
const route = useRoute();

const searchFormState = ref({
  ID: 0,
  DeptID: 0,
  RoleID: 0,
  UserName: "",
  IsEnable: -1,
});
const formRef = ref();

const tableRef = ref();
const toolConfig = {
  refresh: true,
  height: true,
  columnSetting: false,
  striped: false,
};
const columns = [
  {
    title: "用户名",
    dataIndex: "UserName",
    align: "center",
  },
  {
    title: "是否启用",
    dataIndex: "IsEnable",
    align: "center",
  },
  {
    title: "角色ID",
    dataIndex: "RoleID",
    align: "center",
  },
  {
    title: "部门ID",
    dataIndex: "DeptID",
    align: "center",
  },
  {
    title: "最近登录时间",
    dataIndex: "UpdateTime",
    align: "center",
  },
  {
    title: "说明",
    dataIndex: "UserDesp",
    align: "center",
  },

  {
    title: "角色名称",
    dataIndex: "RoleName",
    align: "center",
  },
  {
    title: "部门名称",
    dataIndex: "DeptName",
    align: "center",
  },
  {
    title: "操作",
    dataIndex: "action",
    align: "center",
   
  },
];
// 列表选择配置
const options = {
  alert: {
    show: false,
    clear: () => {
      selectedRowKeys = ref([]);
    },
  },
};
const searchFormRef = ref();
const reset = () => {
  searchFormRef.value.resetFields();
  tableRef.value.refresh(true);
};

const loadData = (parameter) => {
  return usermgrApi
    .getUsers(Object.assign(parameter, searchFormState.value))
    .then((res) => {
      return res;
    });
};
// 删除
const deleteModule = (record) => {
  let params = {
    ID: record.ID,
    UserName: record.UserName,
  };
  usermgrApi.deleteUser(params).then(() => {
    message.success("删除成功");
    tableRef.value.refresh();
  });
};
const changeEnable = (bool, record) => {
  let code = bool ? 1 : 0;
  usermgrApi
    .modifyUser({
      ID: record.ID,
      UserName: record.UserName,
      RoleID: record.RoleID,
      DeptID: record.DeptID,
      IsEnable: code,
      UserDesp: record.UserDesp,
    })
    .then(() => {
      message.success("修改成功");
      tableRef.value.refresh();
    });
};

/* 
以下是修改用户密码部分

*/
let record = ref({});
const changePassword = (data) => {
  open.value = true;
  record.value = data;
};

// 修改密码弹窗
const open = ref(false);

// 密码强度
let percent = ref(0);
// 表单实例
const passwordFormRef = ref();
// 表单数据
const passwordFormState = ref({});
const regex1 =
  /^(?=.{6,}$)(?:(?=.*[a-zA-Z]).*[a-zA-Z]{6,}|(?=.*\d).*\d{6,}|(?=.*[\W_]).*[\W_]{6,})$/;
const regex2 =
  /^(?=.*[a-zA-Z])(?=.*\d|.*[^a-zA-Z\d])(?=.*\d|.*[a-zA-Z])[a-zA-Z\d^!@#$%^&*()_\-+=~`\{\}\[\]\|\\:;\"'<>,.?/]{6,}$/;

// 设置新密码

const setNewPassword = (e) => {
  let value = e.target.value;
  passwordFormState.value.NewPwd = value;

  if (value.length < 1) {
    percent.value = 0;
  } else if (value.length > 0 && value.length < 6) {
    percent.value = 1;
    // 当密码长度大于6时，判断是否包含数字、大小写字母和特殊字符
  } else if (value.length >= 6) {
    if (regex1.test(value)) {
      percent.value = 2;
    } else {
      percent.value = 1;
    }
    if (regex2.test(value)) {
      percent.value = 3;
    } else {
      percent.value = 2;
    }
  }
};
const formRules = {
  NewPwd: [required("请输入新密码")],
};
const handleOk = () => {
  passwordFormRef.value.validate().then(() => {
    if (percent.value != 3) {
      message.error(
        "密码强度不够,请至少输入6位密码,包含数字,字母,特殊字符中的两种"
      );
      return;
    }
    let newPassword = passwordFormState.value.NewPwd.toString();
    loginApi
      .modifyUserPwd({
        UserID: record.value.ID,
        NewPwd: CryptoJS.MD5(newPassword).toString(),
      })
      .then((res) => {
        open.value = false;
        message.success("修改密码成功");
        tableRef.value.refresh();
      })
      .catch((err) => {
        console.log(err);
      });
  });
};
// 查询用户角色
let formRoleList = ref([]);
let _formRoleList = ref([]);
const fetchRolemgr = () => {
  rolemgrApi
    .getRoles({
      ID: 0,
      RoleName: "",
    })
    .then((res) => {
      formRoleList.value = res.Data.map((i) => {
        return {
          label: i.RoleName,
          value: i.ID,
        };
      });
      _formRoleList.value = JSON.parse(JSON.stringify(formRoleList.value));
      formRoleList.value.unshift({
        label: "全部",
        value: 0,
      });
    });
};
// 查询部门
let deptmgrList = ref([]);
let _deptmgrList = ref([]);
const fetchdeptmgr = () => {
  deptmgrList.value = [];
  deptmgrApi
    .getDepts({
      ID: 0,
      PID: 0,
      DeptName: "",
    })
    .then((res) => {
      if (res.Data[0]) {
        flatDeptmgrList(res.Data);
        deptmgrList.value = deptmgrList.value.map((i) => {
          return {
            label: i.DeptName,
            value: i.ID,
          };
        });
        _deptmgrList.value = JSON.parse(JSON.stringify(deptmgrList.value));
        deptmgrList.value.unshift({
          label: "全部",
          value: 0,
        });
        console.log(deptmgrList.value);

      }
    });
};
// 进行扁平化
const flatDeptmgrList = (params) => {
  params.forEach((item) => {
    deptmgrList.value.push(item);
    if (item.Childs) {
      flatDeptmgrList(item.Childs);
      delete item.Childs;
    }
  });
};

onMounted(() => {
  fetchRolemgr();
  fetchdeptmgr();
});
</script>
  <style lang="scss" scoped>
.deptmgr {
  width: 100%;
  height: 100%;
  padding: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  overflow: hidden;
  & > div {
    height: 100%;
    overflow: auto;
  }
  .deptmgr_tree {
    flex: 3;
    margin-right: 10px;
  }
  .deptmgr_content {
    flex: 8;
  }
}
.progress {
  height: 100%;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  & > div {
    height: 6px;
    width: 340px;
    background-color: #f0f0f0;
    margin-right: 5px;
  }
  .progress_c_1 {
    background-color: #f5222d;
  }
  .progress_c_2 {
    background-color: #e6e20b;
  }
  .progress_c_3 {
    background-color: #52c41a;
  }
}
.checkoutBox {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  height: 100%;
}
.checkout {
  border-radius: 100%;
  width: 24px;
  height: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #52c41a;
}
</style>
    